package com.sgb.kjwl.view.ui.activity.self.packers;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtSelfBasicInfoBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.utils.NumberConstant;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamIntroduceEntity;
import com.sgb.kjwl.model.entity.self.SelfWorkerPublishEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.kjwl.view.ui.adapter.self.packers.SelfLabelAdapter;
import com.sgb.link.view.adapter.SelfTeamPicAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.WorkTypeSelectWindow;
import com.sgb.kjwl.viewmodel.self.packers.SelfBasicInformationModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.GlideRoundTransform;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;


/**
 * description:发布工人-基础信息
 *
 * @author LiWei
 * @date 2020/12/19
 */
public class SelfBasicInformationActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    @Inject
    SelfBasicInformationModel viewModel;
    private AtSelfBasicInfoBinding binding;
    private SelfWorkerPublishEntity mEntity;

    private SelfLabelAdapter labelAdapter;

    private List<PickSelectEntity> pickIndustry;
    private List<PickSelectEntity> pickWorkLevel;

    private List<String> workTypeListNO;

    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;

    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private int sexSelectPosition;

    private String industryNo = "";
    private String categoryNo = "";

    public static final int REQUEST_AVATAR_CODE = 10105;
    private String avatar = "";

    private RequestManager requestManager;
    private Map<String, String> mCacheImgMap;
    private SelfTeamPicAdapter mPicAdapter;
    private List<String> mUploadImgList;
    private int mCurPicNum;
    private String age;
    private String sexName;
    private String sexNo;
    private String workAge;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, SelfBasicInformationActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().
                appComponent(appComponent).selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void initView() {
        requestManager = Glide.with(this);
        binding = DataBindingUtil.setContentView(this, R.layout.at_self_basic_info);
        binding.setViewModel(null);
        binding.ivWorkerAvatar.setOnClickListener(this);
        binding.etIndustryType.setOnWholeItemClickListener(this);
        binding.etCategoryType.setOnWholeItemClickListener(this);
        binding.etWorkType.setOnWholeItemClickListener(this);
        binding.etProficiency.setOnWholeItemClickListener(this);
        binding.etWorkAge.setOnWholeItemClickListener(this);
        binding.etArea.setOnWholeItemClickListener(this);
        binding.llNation.setOnClickListener(this);
        binding.ivNation.setOnClickListener(this);
        binding.etWorkAddress.setOnWholeItemClickListener(this);
        binding.llHometown.setOnClickListener(this);
        binding.ivHometown.setOnClickListener(this);
        binding.btnEdit.setOnClickListener(this);
        binding.tvWorking.setOnClickListener(this);
        binding.tvNotWork.setOnClickListener(this);
        binding.etWorkerSex.setOnWholeItemClickListener(this);
        binding.etWorkerAge.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.etWorkAge.setInputType(InputType.TYPE_CLASS_NUMBER);

        age = getIntent().getStringExtra("age");
        int sexSelectPosition = getIntent().getIntExtra("sexSelectPosition", 0);
        sexName = getIntent().getStringExtra("sexName");
        sexNo = getIntent().getStringExtra("sexNo");
        workAge = getIntent().getStringExtra("workAge");

        if (!TextUtils.isEmpty(age)) {
            this.sexSelectPosition = sexSelectPosition;
        }

        initPic();
    }

    @Override
    protected void init() {
        viewModel.getTeamInfoLabel();
        viewModel.getWorkerDetail();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_worker_avatar) {
            viewModel.pictureSelector(1, REQUEST_AVATAR_CODE);
        } else if (id == R.id.tv_working) {
            changeStatus(1);
        } else if (id == R.id.tv_not_work) {
            changeStatus(0);
        } else if (id == R.id.btn_edit) {
            if (TextUtils.isEmpty(binding.etWorkerAge.getContent())) {
                MToast.showToast(this, binding.etWorkerAge.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etIndustryType.getContent())) {
                MToast.showToast(this, binding.etIndustryType.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etCategoryType.getContent())) {
                MToast.showToast(this, binding.etCategoryType.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkType.getContent())) {
                MToast.showToast(this, binding.etWorkType.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkerSex.getContent())) {
                MToast.showToast(this, binding.etWorkerSex.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etProficiency.getContent())) {
                MToast.showToast(this, binding.etProficiency.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkAge.getContent())) {
                MToast.showToast(this, binding.etWorkAge.getContent_edt().getHint().toString());
                return;
            }
            if (Integer.parseInt(binding.etWorkerAge.getContent()) < Integer.parseInt(binding.etWorkAge.getContent())) {
                MToast.showToast(this, "工龄不可以超过年龄");
                return;
            }
            if (TextUtils.isEmpty(binding.etArea.getContent())) {
                MToast.showToast(this, binding.etArea.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkAddress.getContent())) {
                MToast.showToast(this, binding.etWorkAddress.getContent_edt().getHint().toString());
                return;
            }
            mEntity.setAge(binding.etWorkerAge.getContent());
            mEntity.setWorkYear(binding.etWorkAge.getContent());
            mEntity.setIntroduce(binding.etSelfIntroduction.getEditContent());
            mUploadImgList.clear();
            mCurPicNum = -1;
            uploadAvatar();
        } else if (id == R.id.ll_nation) {
            viewModel.getNationList();
        } else if (id == R.id.iv_nation) {
            binding.ivNation.setVisibility(View.GONE);
            binding.etNation.setText("");
            mEntity.setNation("");
            mEntity.setNationName("");
        } else if (id == R.id.ll_hometown) {
            viewModel.showAddressPop();
        } else if (id == R.id.iv_hometown) {
            binding.ivHometown.setVisibility(View.GONE);
            binding.tvNameHometown.setText("");
            mEntity.setLegalProvName("");
            mEntity.setLegalCityName("");
            mEntity.setLegalProvNo("");
            mEntity.setLegalCityNo("");
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.et_industry_type) {
            if (null == pickIndustry) {
                viewModel.getListIndustrySelect();
            } else {
                showPickIndustryPop(pickIndustry);
            }
        } else if (id == R.id.et_category_type) {
            viewModel.getListCategorySelect(industryNo);
        } else if (id == R.id.et_work_type) {
            viewModel.getWorkType(categoryNo);
        } else if (id == R.id.et_proficiency) {
            if (null == pickWorkLevel) {
                viewModel.getWorkLevel();
            } else {
                showPickWorkLevelPop(pickWorkLevel);
            }
        } else if (id == R.id.et_area) {
            if (addressEntityList != null) {
                showCityPop();
            } else {
                viewModel.getAddressModel();
            }
        } else if (id == R.id.et_work_address) {
            SelfServiceAreaActivity.start(this, mEntity.getWorkArea(), AppConstant.REQ_SERVICE, "工作范围");
        } else if (id == R.id.et_worker_sex) {
            showSexFsPop(viewModel.getSex());
        }
    }

    private void initPic() {
        mCacheImgMap = new HashMap<>();
        mUploadImgList = new ArrayList<>();
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        binding.rvPic.setLayoutManager(manager);
        mPicAdapter = new SelfTeamPicAdapter(this, new ArrayList<>(), 3, manager);
        binding.rvPic.setHasFixedSize(false);
        binding.rvPic.setAdapter(mPicAdapter);
        mPicAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    viewModel.pictureSelector(mPicAdapter.hasCount(), PictureConfig.CHOOSE_REQUEST);
                } else {
                    List<String> newImg = new ArrayList<>();
                    if (mPicAdapter.getDatas() != null && mPicAdapter.getDatas().size() != 0) {
                        if ("add".equals(mPicAdapter.getDatas().get(mPicAdapter.getDatas().size() - 1))) {
                            for (int i = 0; i < mPicAdapter.getDatas().size(); i++) {
                                if (i != mPicAdapter.getDatas().size() - 1) {
                                    newImg.add(mPicAdapter.getDatas().get(i));
                                }
                            }
                        }
                    }
                    Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) mPicAdapter.getDatas());
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
                    startActivity(intent);
                }
            }
        });
    }

    public void updateWorkerEntity(SelfWorkerPublishEntity data) {
        if (data != null) {
            mEntity = data;

            if (!TextUtils.isEmpty(age)) {
                mEntity.setAge(age);
                mEntity.setSex(Integer.parseInt(sexNo));
                mEntity.setWorkYear(workAge);

                data.setAge(age);
                data.setSex(Integer.parseInt(sexNo));
                data.setWorkYear(workAge);
            }
            binding.setViewModel(data);
            binding.tvPhone.setText(String.format("联系电话：%s", data.getContactPhone()));
            changeStatus(data.getWorkStatus());
            industryNo = data.getIndustryNo();
            categoryNo = data.getCategoryNo();
            if (TextUtils.isEmpty(data.getAvatarAddress())) {
                requestManager.load(R.mipmap.worker_avatar).into(binding.ivWorkerAvatar);
            } else {
                RequestOptions options = new RequestOptions();
                options.transform(new GlideRoundTransform(this, 5));
                requestManager.load(data.getAvatarAddress()).apply(options).into(binding.ivWorkerAvatar);
            }
            if (!TextUtils.isEmpty(data.getCategoryName())) {
                binding.etCategoryType.setVisibility(View.VISIBLE);
                binding.etCategoryType.setContent(data.getCategoryName());
            }
            if (!TextUtils.isEmpty(data.getWorkTypeName())) {
                binding.etWorkType.setVisibility(View.VISIBLE);
                binding.etWorkType.setContent(data.getWorkTypeName());
            }
            if (data.getSex() == 1) {
                binding.etWorkerSex.setContent("男");
                sexSelectPosition = 0;
            }
            if (data.getSex() == 2) {
                binding.etWorkerSex.setContent("女");
                sexSelectPosition = 1;
            }
            if (!TextUtils.isEmpty(data.getLegalProvName())) {
                binding.tvNameHometown.setText(String.format("%s%s", data.getLegalProvName(), data.getLegalCityName()));
            }

            if (!TextUtils.isEmpty(data.getNationName())) {
                binding.etNation.setText(data.getNationName());
            }

            if (!TextUtils.isEmpty(data.getProvinceName())) {
                binding.etArea.setContent(data.getProvinceName() + data.getCityName() + data.getAreaName());
            }
            setCheckDefaultList(data.getLabel());
            if (mEntity.getHealthImg() != null && mEntity.getHealthImg().size() > 0) {
                mUploadImgList.addAll(mEntity.getHealthImg());
                mPicAdapter.setData(mUploadImgList);
            }

            if (!TextUtils.isEmpty(age)) {
                binding.etWorkerAge.setContent(age);
                binding.etWorkAge.setContent(workAge);

                binding.etWorkerSex.setContent(sexName);
                mEntity.setSex(Integer.parseInt(sexNo));
            }

            if (!TextUtils.isEmpty(binding.etNation.getText().toString())) {
                binding.ivNation.setVisibility(View.VISIBLE);
            }

            if (!TextUtils.isEmpty(binding.tvNameHometown.getText().toString())) {
                binding.ivHometown.setVisibility(View.VISIBLE);
            }
        } else {
            mEntity = new SelfWorkerPublishEntity();
            viewModel.getUserInfo();

            if (!TextUtils.isEmpty(age)) {
                binding.etWorkerAge.setContent(age);
                binding.etWorkAge.setContent(workAge);

                binding.etWorkerSex.setContent(sexName);
                mEntity.setSex(Integer.parseInt(sexNo));
            }
        }
    }

    private void changeStatus(int status) {
        switch (status) {
            case 1:
                binding.tvWorking.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_self_worker_working_frame));
                binding.tvNotWork.setBackground(null);
                binding.tvWorking.setTextColor(ContextCompat.getColor(this, R.color.color_FFFFFF));
                binding.tvNotWork.setTextColor(ContextCompat.getColor(this, R.color.new_org2));
                if(mEntity!=null){
                    mEntity.setWorkStatus(1);
                }

                break;
            case 0:
                binding.tvWorking.setBackground(null);
                binding.tvNotWork.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_self_worker_work_not_frame));
                binding.tvWorking.setTextColor(ContextCompat.getColor(this, R.color.new_org2));
                binding.tvNotWork.setTextColor(ContextCompat.getColor(this, R.color.color_FFFFFF));
                if(mEntity!=null){
                    mEntity.setWorkStatus(0);
                }
                break;
        }
    }

    private void uploadAvatar() {
        //过滤已上传头像且上传新头像
        if (TextUtils.isEmpty(mEntity.getAvatarAddress()) || !TextUtils.isEmpty(avatar)) {
            if (null != avatar && !TextUtils.isEmpty(avatar)) {
                File file = new File(avatar);
                viewModel.uploadAvatarFileModel(file, 1);
            } else {
                uploadPic();
            }
        } else {
            uploadPic();
        }
    }

    public void setLabelAdapterData(List<PickSelectEntity> labelList) {
        List<String> stringList = new ArrayList<>();
        if (labelAdapter == null) {
            labelAdapter = new SelfLabelAdapter(this, labelList);
        }
        binding.maxRec.setLayoutManager(new GridLayoutManager(this, 4));
        binding.maxRec.setAdapter(labelAdapter);
        labelAdapter.setMultiSelect(true);
        labelAdapter.setMost(3);
        labelAdapter.setOnItemMultiClick((pickSelectEntities, position) -> {
            stringList.clear();
            for (PickSelectEntity entity : pickSelectEntities) {
                stringList.add(entity.getNo());
            }
            mEntity.setLabel(stringList);
        });
    }

    public void setCheckDefaultList(List<String> checkDefaultList) {
        if (checkDefaultList != null && labelAdapter != null) {
            for (String s : checkDefaultList) {
                labelAdapter.setCheckDefault(Integer.parseInt(s) - 1);
            }
        }
    }

    // 上传头像回调
    public void uploadAvatarResult(String toString) {
        mEntity.setAvatarAddress(toString);
        avatar = null;
        uploadPic();
    }

    // 籍贯选择回调
    public void updateAddress(PickSelectEntity<List<PickSelectEntity>> opt1, PickSelectEntity opt2) {
        mEntity.setLegalProvName(opt1.getProjectscale());
        mEntity.setLegalCityName(opt2.getProjectscale());
        mEntity.setLegalProvNo(opt1.getNo());
        mEntity.setLegalCityNo(opt2.getNo());
        binding.tvNameHometown.setText(String.format("%s%s", opt1.getProjectscale(), opt2.getProjectscale()));
        binding.ivHometown.setVisibility(View.VISIBLE);
    }


    /**
     * 性别
     *
     * @param list 性别选择器的数据
     */
    public void showSexFsPop(List<PickSelectEntity> list) {
        OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfBasicInformationActivity.this, (options1, options2, options3, v) -> {
            binding.etWorkerSex.setContent(list.get(options1).getProjectscale());
            mEntity.setSex(Integer.parseInt(list.get(options1).getNo()));
            sexSelectPosition = options1;
        }).build();
        projectCategoryOption.setPicker(viewModel.getSex());
        projectCategoryOption.setSelectOptions(sexSelectPosition);
        projectCategoryOption.setTitleText("请选择性别");
        projectCategoryOption.show();
    }

    public void showPickIndustryPop(List<PickSelectEntity> list) {
        if (null == pickIndustry) {
            pickIndustry = new ArrayList<>();
            pickIndustry.addAll(list);
        }
        if (pickIndustry.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfBasicInformationActivity.this, (options1, options2, options3, v) -> {
                binding.etIndustryType.setContent(pickIndustry.get(options1).getProjectscale());
                if (mEntity != null) {
                    mEntity.setIndustryNo(pickIndustry.get(options1).getNo() + "");
                    mEntity.setIndustryName(pickIndustry.get(options1).getProjectscale());
                }
                industryNo = pickIndustry.get(options1).getNo();
                binding.etCategoryType.setVisibility(View.VISIBLE);
                binding.etCategoryType.setContent("");
                binding.etWorkType.setVisibility(View.GONE);
            }).build();
            projectCategoryOption.setPicker(pickIndustry);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    public void showPickCategoryPop(List<PickSelectEntity> list) {
        if (list.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfBasicInformationActivity.this, (options1, options2, options3, v) -> {
                binding.etCategoryType.setContent(list.get(options1).getProjectscale());
                mEntity.setCategoryNo(list.get(options1).getNo());
                mEntity.setCategoryName(list.get(options1).getProjectscale());
                categoryNo = list.get(options1).getNo();
                binding.etWorkType.setContent("");
                binding.etWorkType.setVisibility(View.VISIBLE);
            }).build();
            projectCategoryOption.setPicker(list);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    public void showPickWorkTypePop(List<PickSelectEntity> list) {
        if (list.size() > 0) {
            WorkTypeSelectWindow typeSelectWindow = new WorkTypeSelectWindow(SelfBasicInformationActivity.this);
            typeSelectWindow.setSelectResultClick((pickSelectEntities, name) -> {
                workTypeListNO = new ArrayList<>();
                for (PickSelectEntity pickSelectEntity : pickSelectEntities) {
                    workTypeListNO.add(pickSelectEntity.getNo());
                }
                mEntity.setWorkType(workTypeListNO);
                binding.etWorkType.setContent(name);
            });
            typeSelectWindow.setMostSelected(3);
            typeSelectWindow.setBgView(binding.grayLayout);
            typeSelectWindow.setWorkTypeData(list);
            typeSelectWindow.showPopwindow(binding.etWorkType);
        }
    }

    public void showPickWorkLevelPop(List<PickSelectEntity> list) {
        if (null == pickWorkLevel) {
            pickWorkLevel = new ArrayList<>();
            pickWorkLevel.addAll(list);
        }
        if (pickWorkLevel.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfBasicInformationActivity.this, (options1, options2, options3, v) -> {
                binding.etProficiency.setContent(pickWorkLevel.get(options1).getProjectscale());
                mEntity.setProficiency(pickWorkLevel.get(options1).getNo());
                mEntity.setProficiencyName(pickWorkLevel.get(options1).getProjectscale());
            }).build();
            projectCategoryOption.setPicker(pickWorkLevel);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    /**
     * 所在地区选择
     *
     * @param data 地区的数据
     */
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(SelfBasicInformationActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                mEntity.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                mEntity.setAreaName(areaName);
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.etArea.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            mEntity.setProvinceName(addressEntityList.get(options1).getName());
            mEntity.setProvinceNo(addressEntityList.get(options1).getId());
            mEntity.setCityName(opt2.get(options1).get(options2).getName());
            mEntity.setCityNo(opt2.get(options1).get(options2).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        //如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
            }
            return false;
        }
    });

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (mEntity != null && mEntity.getProvinceName() != null && mEntity.getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (mEntity != null) {
            if (mEntity.getCityName() != null) {
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (mEntity.getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            }
            if (mEntity.getAreaName() != null) {
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (mEntity.getAreaName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_AVATAR_CODE) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                RequestOptions options = new RequestOptions();
                options.transform(new GlideRoundTransform(this, 5));
                Glide.with(this).load(selectList.get(0).getRealPath()).apply(options).into(binding.ivWorkerAvatar);
                avatar = selectList.get(0).getRealPath();
            }
            if (requestCode == AppConstant.REQ_SERVICE) {
                if (data != null) {
                    List<SelfTeamIntroduceEntity.ServiceAreasBean> serviceAreasBeans = (List<SelfTeamIntroduceEntity.ServiceAreasBean>) data.getSerializableExtra(AppConstant.EXTRA_OBJ);
                    mEntity.setWorkArea(serviceAreasBeans);
                    if (serviceAreasBeans.size() > 0) {
                        StringBuilder stringBuilder = new StringBuilder();
                        for (SelfTeamIntroduceEntity.ServiceAreasBean bean : serviceAreasBeans) {
                            stringBuilder.append(bean.getName()).append("、");
                        }
                        binding.etWorkAddress.setContent(stringBuilder.substring(0, stringBuilder.length() - 1));
                    } else {
                        binding.etWorkAddress.setContent("");
                        MToast.showToast(SelfBasicInformationActivity.this, "至少选择一个工作范围地址");
                    }
                }
            }
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                mPicAdapter.setPicData(selectList);
            }
        }
    }

    /**
     * 发布修改数据成功
     */
    public void editEntitySuccess() {
        WebEvent webEvent = new WebEvent();
        webEvent.setMessageTag(EventConstant.EVENT_WEBVIEW_RELOAD);
        EventBus.getDefault().post(webEvent);
        NumberConstant.sIsBack = 1;
        finish();
    }

    public void showUserInfo(UserMsgEntity data) {
        binding.name.setText(data.getRealName());
        binding.tvPhone.setText(String.format("联系电话：%s", data.getTelPhone()));
        mEntity.setName(data.getRealName());
        mEntity.setContactPhone(data.getTelPhone());
    }

    public void uploadPicInfo(String absolutePath, String toString) {
        mUploadImgList.add(toString);
        mCacheImgMap.put(absolutePath, toString);
        uploadPic();
    }

    private void uploadPic() {
        mCurPicNum++;
        int size = mPicAdapter.getRealCount();
        if (size > 0 && mCurPicNum < size) {
            String path = mPicAdapter.getDatas().get(mCurPicNum);
            if (path.startsWith("http")) {
                // 保存已上传图片
                mUploadImgList.add(path);
                uploadPic();
            } else {
                // 过滤已上传的
                if (!TextUtils.isEmpty(mCacheImgMap.get(path))) {
                    mUploadImgList.add(mCacheImgMap.get(path));
                    uploadPic();
                } else {
                    File file = new File(mPicAdapter.getDatas().get(mCurPicNum));
                    viewModel.uploadMultiFileModel(file, mCurPicNum + 1, size);
                }
            }
        } else {
            release();
        }
    }

    private void release() {
        mEntity.setHealthImg(mUploadImgList);
        viewModel.addWorker(mEntity);
    }

    private List<PickSelectEntity> pickNation;

    public void showNationPop(List<PickSelectEntity> list) {
        if (null == pickNation) {
            pickNation = new ArrayList<>();
            pickNation.addAll(list);
        }
        if (pickNation.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfBasicInformationActivity.this, (options1, options2, options3, v) -> {
                binding.etNation.setText(pickNation.get(options1).getProjectscale());
                mEntity.setNation(pickNation.get(options1).getNo());
                mEntity.setNationName(pickNation.get(options1).getProjectscale());
                binding.ivNation.setVisibility(View.VISIBLE);
            }).build();
            projectCategoryOption.setPicker(pickNation);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

}
